package com.nowadays.mobile.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ForegroundChangeHelper implements Application.ActivityLifecycleCallbacks {
  private static int compatStartCount = 0;
  private static boolean isCompatForeground = true;

  private static List<WeakReference<OnAppForegroundChangeListener>> foregroundChangeListenerList = new ArrayList<>();

  private static volatile ForegroundChangeHelper helper;

  public static ForegroundChangeHelper getInstance() {
    if (helper == null) {
      synchronized (ForegroundChangeHelper.class) {
        if (helper == null) {
          helper = new ForegroundChangeHelper();
        }
      }
    }
    return helper;
  }

  public interface OnAppForegroundChangeListener {
    void onForegroundToBackground();

    void onBackgroundToForeground();
  }

  public void add2ForegroundChangeListenerList(WeakReference<OnAppForegroundChangeListener> listener) {
    if (!foregroundChangeListenerList.contains(listener)) {
      foregroundChangeListenerList.add(listener);
    }
  }

  @Override
  public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

  }

  @Override
  public void onActivityStarted(Activity activity) {
    compatStartCount++;
    if (!isCompatForeground) {
      isCompatForeground = true;
      for(WeakReference<OnAppForegroundChangeListener> listener :foregroundChangeListenerList) {
        listener.get().onBackgroundToForeground();
      }
    }
  }

  @Override
  public void onActivityResumed(Activity activity) {

  }

  @Override
  public void onActivityPaused(Activity activity) {

  }

  @Override
  public void onActivityStopped(Activity activity) {
    compatStartCount--;
    if (compatStartCount == 0) {
      isCompatForeground = false;
      for (WeakReference<OnAppForegroundChangeListener> listener :foregroundChangeListenerList) {
        listener.get().onForegroundToBackground();
      }
    }
  }

  @Override
  public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

  }

  @Override
  public void onActivityDestroyed(Activity activity) {

  }
}
